<?php

require dirname(__FILE__) . '/includes/Product.class.php';
require dirname(__FILE__) . '/includes/ProductSearch.class.php';
require dirname(__FILE__) . '/includes/Basket.class.php';
require dirname(__FILE__) . '/includes/modifier.format_price.php';
require dirname(__FILE__) . '/includes/SagePay.class.php';

$currencies = array_index($db->fetchAll("SELECT * FROM shop_currencies"), 'iso');
if (isset($_REQUEST['currency'])) {
	if ($db->fetchOne("SELECT iso FROM shop_currencies WHERE iso=?", strtoupper($_REQUEST['currency']))) {
		$_SESSION['currency'] = strtoupper($_REQUEST['currency']);
	}
}


$shop_images_raw = glob($app_root . $site['home_dir'] . '/shop-images/*/*.jpg');
sort($shop_images_raw);
$shop_images = array();
foreach($shop_images_raw as $image) {
	$detail = preg_extract('#/([^/]*?)/(([^/]*?)(?:_\d+)?\.jpg)$#', $image);
	$shop_images[$detail[0]][$detail[2]][] = $detail[1];
}


function shop_get_images($type, $match) {
	global $shop_images;
	if (isset($shop_images[$type][$match])) return $shop_images[$type][$match];
}


$basket = new Basket();
$smarty->assign('basket', $basket->export());

foreach($_REQUEST as $k => $v) {
	if ($filter = preg_extract('/^f:([a-z]+)$/', $k)) {
		header("Location: " . $page['full_path'] . (count($path) ? join('/', $path) . '/' : '') . $filter[0] . ':' . urlencode($v) . '/');
		exit;
	}
}

if (!isset($path[0])) {
	$index = $smarty->fetch('shop/index.tpl.html');
	if (!$index) return 0;
	echo $index;
}

elseif (in_array($path[0], array('basket', 'checkout', 'wishlist', 'shop-images', 'benchmark', 'search', 'addresses', 'account', 'orders'))) {
	require(dirname(__FILE__) . '/' . array_shift($path) . '.php');
}

else {
	
	if ($product_id = $db->fetchOne("SELECT id FROM shop_products WHERE site_id=? AND path=? AND active=1 AND deleted=0", array($site['id'], $path[0]))) {
		require dirname(__FILE__) . '/product.php';
	} else {
		$filters = array();
		$parent_id = $db->fetchOne("SELECT id FROM shop_categories WHERE site_id=? AND parent_id=0", $site['id']);
		for($i=0;$i<count($path);$i++) {
			if(strpos($path[$i], ':') !== false) {
				$filters[] = $path[$i];
			} elseif ($category = $db->fetchRow("SELECT * FROM shop_categories WHERE site_id=? AND path=? AND parent_id=?", array($site['id'], $path[$i], $parent_id))) {
				$parent_id = $category['id'];
			} else {
				return;
			}
		}
		
		if (!isset($category)) {
			$category = array(
				'id'            => 0,
				'display'       => 'products',
				'title'         => 'Search results',
				'default_order' => '',
				'search'        => true
			);
		}
		
		require dirname(__FILE__) . '/category.php';
		
	}
	
}
